package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.SignonCriteria;
import com.leo.ibatis.demo.dao.SignonDao;
import com.leo.ibatis.demo.domain.Signon;
import com.leo.ibatis.demo.util.Paging;

public class SignonDaoImpl extends SqlMapClientDaoSupport implements SignonDao {

	public void insert(Signon signon) throws DataAccessException {
		getSqlMapClientTemplate().insert("Signon.insert", signon);
	}

	public int update(Signon signon) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Signon.update", signon, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String username) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Signon.delete", username, actualRowsAffected);

		return actualRowsAffected;
	}

	public Signon select(String username) throws DataAccessException {
		return (Signon) getSqlMapClientTemplate().queryForObject("Signon.select", username);
	}

	@SuppressWarnings("unchecked")
	public List<Signon> list(SignonCriteria signonCriteria) throws DataAccessException {
		Assert.notNull(signonCriteria, "signonCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Signon.list", signonCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Signon> listOnPage(SignonCriteria signonCriteria) throws DataAccessException {
		Assert.notNull(signonCriteria, "signonCriteria must not be null");
		Assert.notNull(signonCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(signonCriteria);
		Paging paging = signonCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Signon.list", signonCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(SignonCriteria signonCriteria) throws DataAccessException {
		Assert.notNull(signonCriteria, "signonCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Signon.count", signonCriteria)).intValue();
	}

}
